#' @title return demo plots for barplot (get label position based on mean+se).
#' @details demo to draw plots with the results in ggplot2.
#' @param obj obj
#' @return obj with demo codes.

get_demo_codes_for_bar_plots <- function(obj = obj){
    codes <- "
obj <- get_pic_with_labels(input_df = iris[,1:4,drop = F],
                           # input_df$Sepal.Length <- rnorm(nrow(input_df)),
                           group_info_df = iris[,5,drop = F],
                           group_index = 1,
                           group_levels_in_order_C = group_info_df[,1] %>% unique(),
                           test_pattern  = 'para' ,
                           # test_pattern  = 'wise' ,
                           # test_pattern  = 'non-para' %>% tolower(),
                           p_for_label = 'p_all',
                           unify_step_as_constant = T, ### Very important when drawing different variables in same row(with fixed y value.)
                           step = 0.15, # Modify the vertical distances between significant label codes.
                           draw_pics = F, 
                           position_by = 'max meanse')


variables_c <- obj@pic_long_df$variable %>% unique
page_num <- variables_c %>% length
segment_size <- .7 ## The size of the segement
# each_page <- 1
obj@pic_long_df
# for(each_page in 1:page_num){

# each_meta <- variables_c[each_page]
obj@pic_long_df %>% head
pic <- ggplot(obj@pic_long_df) + 
    ## error bar by mean ± se
    geom_errorbar( aes(x= group, ymin=mean-se, ymax=mean+se),  
                   width=0.4, colour='black', alpha=0.9, size=1.3) +
    geom_bar(aes(x = group, y = mean, group = group, fill = group), data = obj@pic_long_df , 
             # size  = .8,
             position = position_dodge(),
             stat='identity'
             # outlier.colour = 'white',
             # width = 2,
             
    )+
    theme_bw()+
    facet_wrap(facets = vars(variable), nrow = 1, scales = 'fixed')+
    theme(
        text = element_text(size = 18, color = 'black'),
        axis.text.y = element_text( size = 12, face = 'bold', color = 'black'),
        axis.text.x = element_text( size = 12, face = 'bold', color = 'black'),
        strip.text.x = element_text(size = 16, color = 'black'),
        panel.grid = element_blank()
    )
pic
pic <- pic +
    geom_segment(data = obj@label_position_df,
                 aes(x = start_num, xend = start_num + 0.25 * (end_num - start_num),
                     y = label.y, yend = label.y), lineend = 'butt', size = segment_size)+
    geom_segment(data = obj@label_position_df, 
                 aes(x = end_num, xend = start_num + 0.75 * (end_num - start_num),
                     y = label.y, yend = label.y), 
                 lineend = 'butt', size = segment_size)+
    geom_text(data = obj@label_position_df, 
              aes(x = 0.5*(start_num + end_num), y = label.y*1.007, label = label)
              ,color = 'black', size = 8) +
    geom_segment(data = obj@label_position_df, aes(x = start_num, xend = start_num, y = label.y, yend = label.y * .99), lineend = 'round', size = segment_size)+
    geom_segment(data = obj@label_position_df, aes(x = end_num, xend = end_num, y = label.y, yend = label.y * .99), lineend = 'round', size = segment_size)+
    geom_segment(data = obj@label_position_df, aes(x = start_num, xend = end_num, y = label.y, yend = label.y),
                 size = segment_size) + 
    xlab('Group')+
    ylab('Concentration (μmol/L)')+
    scale_y_continuous(expand = expansion(c(0.05,0.05)))
pic

plot_name <- sprintf('plot with sig labels.pdf')

ggsave(plot_name, plot = pic, width = 5, height = 4, 
       limitsize = F, family = 'serif')




df <- data.frame(x = rep(c(2.9, 3.1, 4.5), c(5, 10, 4)))
ggplot(df, aes(x)) + geom_bar()
"
    obj@demo_code_for_barplot <- codes
    return(obj)
}

#' @title get_plot_with_labels
#' @details demo to fraw plots with the results in ggplot2.
#' @param obj obj
#' @return a plot
#' 
draw_plot_with_labels <- function(obj,  draw_pics = draw_pics){
    
    if(draw_pics == T){
        'obj represent the result of the function'
        variables_c <- obj@pic_long_df$variable %>% unique
        page_num <- variables_c %>% length
        segment_size <- .7 ## The size of the segement
        # each_page <- 1
        obj@pic_long_df
        for(each_page in 1:page_num){
            
            each_meta <- variables_c[each_page]
            # each_meta
            
            # pic_df_new$variable <- pic_df_new$variable %>% sub("\\.", " ", .)
            # pic_df_new <- pic_df[pic_df$variable %in% variable,]
            pic <- ggplot(obj@pic_long_df) + 
                # geom_errorbar(aes(x = group,  ymax = mean + se, ymin = mean - se, ## 将最小值藏起来。 
                #                   color = group, group = group),
                #               width = 0.45, size = 0.6, color = "black")+
                ## the key to do this is move aes attr into the following geom_XXXX line. Insdead of the first line.
                # geom_bar(stat  = "identity", aes(x = group, y = mean(value), fill = group, group = group))+
                # geom_bar(aes(x = group, y = mean, fill = group, group = group), 
                #          stat = "identity", position = "identity")+
                # geom_bar(aes(x = group, y = mean/count, fill = group, group = group), stat = "identity", position = "fill")+
                geom_boxplot(aes(x = group, y = value), data = obj@pic_long_df, outlier.colour = "white",
                             # width = 2,
                             size  = .8)+
                theme_bw()+
                # geom_bar(aes(x = group, y = mean, fill = group, group = group), 
                #          stat = "identity", position = "identity")+
                geom_point(aes(x = group, y = value), shape = 21, color = "black", fill = "red", 
                           position = position_jitter(width = .15, height = 0), size = 1.3, alpha = .8)+ 
                # facet_wrap(facets = vars(variable), ncol = 3, scales = "free")+
                facet_wrap_paginate(facets = vars(variable), scales="free", ncol = 1, nrow = 1, page = each_page)+
                # scale_fill_manual(values = color_vector_c)+
                theme(
                    text = element_text(size = 18, color = "black"),
                    # legend.title = element_text(size = 22, color = "black"),
                    # legend.text = element_text(size = 18, color = "black"),
                    axis.text.y = element_text( size = 12, face = "bold", color = "black"),
                    axis.text.x = element_text( size = 12, face = "bold", color = "black"),
                    strip.text.x = element_text(size = 16, color = "black"),
                    # axis.text.x = element_blank(),
                    ### 加横坐标，去除网格线。
                    panel.grid = element_blank()
                )
            
            pic <- pic +
                geom_segment(data = obj@label_position_df,
                             aes(x = start_num, xend = start_num + 0.25 * (end_num - start_num),
                                 y = label.y, yend = label.y), lineend = "butt", size = segment_size)+
                geom_segment(data = obj@label_position_df, 
                             aes(x = end_num, xend = start_num + 0.75 * (end_num - start_num),
                                 y = label.y, yend = label.y), 
                             lineend = "butt", size = segment_size)+
                # geom_shadowtext(data = final_label_df, 
                #                 aes(x = 0.5*(start_num + end_num),
                #                     y = label.y, label = label), 
                #                 size = 5.5, bg.colour='firebrick') + 
                geom_text(data = obj@label_position_df, 
                          aes(x = 0.5*(start_num + end_num), y = label.y*1.007, label = label)
                          ,color = "black", size = 8) +
                geom_segment(data = obj@label_position_df, aes(x = start_num, xend = start_num, y = label.y, yend = label.y * .99), lineend = "round", size = segment_size)+
                geom_segment(data = obj@label_position_df, aes(x = end_num, xend = end_num, y = label.y, yend = label.y * .99), lineend = "round", size = segment_size)+
                # geom_segment(data = final_label_df, aes(x = end_num, xend = end_num, y = label.y, yend = label.y * .99), lineend = "round", size = segment_size) + 
                geom_segment(data = obj@label_position_df, aes(x = start_num, xend = end_num, y = label.y, yend = label.y),
                             size = segment_size) + 
                xlab("Group")+
                ylab("Concentration (μmol/L)")+
                scale_y_continuous(expand = expansion(c(0.05,0.05)))
            ### geom_text can be reguarded as num value when the x shows factor variable.
            
            plot_name <- sprintf("%splot with sig labels #%s.pdf", output_path, each_meta)
            
            ggsave(plot_name, plot = pic, width = 5, height = 4, 
                   limitsize = F, family = "serif")
            
        }
    }
    
    
    demo_code <- "'obj represent the result of the function'
    variables_c <- obj@pic_long_df$variable %>% unique
    page_num <- variables_c %>% length
    segment_size <- .7 ## The size of the segement
    # each_page <- 1
    obj@pic_long_df
    for(each_page in 1:page_num){
        
        each_meta <- variables_c[each_page]

        pic <- ggplot(obj@pic_long_df) + 
            # geom_errorbar(aes(x = group,  ymax = mean + se, ymin = mean - se, ## 将最小值藏起来。 
            #                   color = group, group = group),
            #               width = 0.45, size = 0.6, color = 'black')+
            ## the key to do this is move aes attr into the following geom_XXXX line. Insdead of the first line.
            # geom_bar(stat  = 'identity', aes(x = group, y = mean(value), fill = group, group = group))+
            # geom_bar(aes(x = group, y = mean, fill = group, group = group), 
            #          stat = 'identity', position = 'identity')+
            # geom_bar(aes(x = group, y = mean/count, fill = group, group = group), stat = 'identity', position = 'fill')+
            geom_boxplot(aes(x = group, y = value), data = obj@pic_long_df, outlier.colour = 'white',
                         # width = 2,
                         size  = .8)+
            theme_bw()+
            # geom_bar(aes(x = group, y = mean, fill = group, group = group), 
            #          stat = 'identity', position = 'identity')+
            geom_point(aes(x = group, y = value), shape = 21, color = 'black', fill = 'red', 
                       position = position_jitter(width = .15, height = 0), size = 1.3, alpha = .8)+ 
            # facet_wrap(facets = vars(variable), ncol = 3, scales = 'free')+
            facet_wrap_paginate(facets = vars(variable), scales='free', ncol = 1, nrow = 1, page = each_page)+
            # scale_fill_manual(values = color_vector_c)+
            theme(
                text = element_text(size = 18, color = 'black'),
                # legend.title = element_text(size = 22, color = 'black'),
                # legend.text = element_text(size = 18, color = 'black'),
                axis.text.y = element_text( size = 12, face = 'bold', color = 'black'),
                axis.text.x = element_text( size = 12, face = 'bold', color = 'black'),
                strip.text.x = element_text(size = 16, color = 'black'),
                # axis.text.x = element_blank(),
                ### 加横坐标，去除网格线。
                panel.grid = element_blank()
            )
        
        pic <- pic +
            geom_segment(data = obj@label_position_df,
                         aes(x = start_num, xend = start_num + 0.25 * (end_num - start_num),
                             y = label.y, yend = label.y), lineend = 'butt', size = segment_size)+
            geom_segment(data = obj@label_position_df, 
                         aes(x = end_num, xend = start_num + 0.75 * (end_num - start_num),
                             y = label.y, yend = label.y), 
                         lineend = 'butt', size = segment_size)+
            # geom_shadowtext(data = final_label_df, 
            #                 aes(x = 0.5*(start_num + end_num),
            #                     y = label.y, label = label), 
            #                 size = 5.5, bg.colour='firebrick') + 
            geom_text(data = obj@label_position_df, 
                      aes(x = 0.5*(start_num + end_num), y = label.y*1.007, label = label)
                      ,color = 'black', size = 8) +
            geom_segment(data = obj@label_position_df, aes(x = start_num, xend = start_num, y = label.y, yend = label.y * .99), lineend = 'round', size = segment_size)+
            geom_segment(data = obj@label_position_df, aes(x = end_num, xend = end_num, y = label.y, yend = label.y * .99), lineend = 'round', size = segment_size)+
            # geom_segment(data = final_label_df, aes(x = end_num, xend = end_num, y = label.y, yend = label.y * .99), lineend = 'round', size = segment_size) + 
            geom_segment(data = obj@label_position_df, aes(x = start_num, xend = end_num, y = label.y, yend = label.y),
                         size = segment_size) + 
            xlab('Group')+
            ylab('Concentration (μmol/L)')+
            scale_y_continuous(expand = expansion(c(0.05,0.05)))
        ### geom_text can be reguarded as num value when the x shows factor variable.
        
        plot_name <- sprintf('%splot with sig labels #%s.pdf', output_path, each_meta)
        
        ggsave(plot_name, plot = pic, width = 5, height = 4, 
               limitsize = F, family = 'serif')
        
    }"
    
    obj@demo_code <- demo_code
    
    return(obj)
}

#' @title get_label_position for picture by_max_single_value
#' @param obj the object. all in one.

get_position_by_max_single_value <- function(obj){
    
    final_df <- obj@label_position_df
    
    
    final_df <- order(final_df$variable, final_df$label != "   ",
                      final_df$ylim_max, final_df$range,final_df$start_num) %>% final_df[.,]
    
    # each_df <- final_df[1:4,]
    final_df <- final_df %>% ddply(., "variable", function(each_df){
        sig_counts <- (each_df$label != "   ") %>% sum()
        
        
        if(sig_counts >0){ ## if has some sig pairs. then calculate the position.
            
            ## start calculate the position since the nrow - sig_counts + 1
            needs_position <- (nrow(each_df) - sig_counts + 1):nrow(each_df)
            ## with consideration of the max_value.
            # each_df$label.y[needs_position] <-  each_df$ylim_range[1] * obj@step * seq_along(needs_position) + each_df$ylim_max[needs_position] 
            
            if(length(needs_position)>=1){
                # each_df$label.y[needs_position] <- recheck_label_position(raw_position = each_df$label.y[needs_position], ## original position
                #                                                           max_in_range = each_df$ylim_max[needs_position], ## base supposed to add height on and put label on it.
                #                                                           step_height = each_df$ylim_range[1] * obj@step) ## each_step.
                ### set a function to du this things.
                each_df$label.y[needs_position] <- return_label.y(max_in_range = each_df$ylim_max[needs_position],
                                                                  step_height = each_df$ylim_range[1] * obj@step,
                                                                  obj = obj,
                                                                  ylim_max = each_df$ylim_max,
                                                                  first_stepdown_adjust = 0.7)
                
            }
            
            
            # each_df$label.y_for_total <- each_df$label.y %>% max(., na.rm = T) ### useful for total p mapping.
        }
        each_df$each_step_height <- each_df$ylim_range[1] * obj@step
        return(each_df)
    })
    
    obj@label_position_df <- final_df
    return(obj)
}



# group_pairs_to_show <- list(c("NCD","NCDG"), c("NCD", "HFD"), c("HFD", "HFDG"), c("HFDG", "HFDGA"))
#' @title get_label_position for picture by_max_meanse
#' @param obj the object. all in one.

subset_group_pairs <- function(obj, group_pairs_to_show){
    ori_df <- obj@label_position_df
    for(i in 1:length(group_pairs_to_show)){
        if(i == 1){final <- rep(F, nrow(ori_df))}
        qualified_c <- (ori_df$pair1 == group_pairs_to_show[[i]][1] & ori_df$pair2 == group_pairs_to_show[[i]][2])|(ori_df$pair1 == group_pairs_to_show[[i]][2] & ori_df$pair2 == group_pairs_to_show[[i]][1])
        final <- final|qualified_c
    }
    ori_df <- ori_df[final,]
    obj@label_position_df <- ori_df
    return(obj)
}



#' @title get_label_position for picture by_max_meanse
#' @param obj the object. all in one.
get_position_by_max_meanse <- function(obj){
    
    final_df <- obj@label_position_df
    final_df <- order(final_df$variable, final_df$label != "   ",
                      final_df$maxmeanse, final_df$range,final_df$start_num) %>% final_df[.,]
    # final_df[,c("Variable", "maxmeanse", "pairwise_p.adj_label")]
    
    # final_df
    
    
    final_df <- final_df %>% ddply(., "variable", function(each_df){
        sig_counts <- (each_df$label != "   ") %>% sum()
        ## max mean+sd in the variable to set the scale
        max_value <- each_df$maxmeanse %>% max(., na.rm = T)
        ## with consideration of the max mean+sd value.1
        if(sig_counts >0){ ## if has some sig pairs. then calculate the position.
            
            ## start calculate the position since the nrow - sig_counts + 1
            needs_position <- (nrow(each_df) - sig_counts + 1):nrow(each_df)
            
            # each_df$label.y[needs_position] <- max_value * obj@step * seq_along(needs_position) + each_df$maxmeanse[needs_position] 
            # 
            # each_df$label.y[needs_position] <- recheck_label_position( raw_position =  each_df$label.y[needs_position], ## original position
            #                                                            max_in_range = each_df$maxmeanse[needs_position], ## base supposed to add height on and put label on it.
            #                                                            step_height = max_value * obj@step)
            
            each_df$label.y[needs_position] <- return_label.y(max_in_range = each_df$maxmeanse[needs_position],
                                                              step_height = each_df$ylim_range[1] * obj@step,
                                                              obj = obj,
                                                              ylim_max = each_df$ylim_max,
                                                              first_stepdown_adjust = 0.7)
            
            
            ### useful for total p mapping.
        }
        return(each_df)
    })
    obj@label_position_df <- final_df
    return(obj)
}

#' @title get_label_position for picture.
#' @param obj the object. all in one.

get_label_position_df <- function(obj){
    df_with_labels <- obj@result_df
    summary_of_df <- obj@pic_long_df
    level_to_num_C <-  seq_along(obj@group_levels_in_order_C)
    names(level_to_num_C) <- obj@group_levels_in_order_C
    
    for(i in 1:nrow(df_with_labels)){
        if(i == 1){final_df <- data.frame(stringsAsFactors = F, check.names = F)}
        df <- df_with_labels[i,]
        df <- df %>% mutate(., 
                            start_num = min(df$pair1 %>% level_to_num_C[.], df$pair2 %>% level_to_num_C[.]),
                            end_num = max(df$pair1 %>% level_to_num_C[.], df$pair2 %>% level_to_num_C[.]),
                            range = end_num - start_num)
        # df 
        
        ## qualified_rows selected the group involved in the range of the group. either they are start，ending or the middle part.
        qualified_rows <- summary_of_df$variable == df$variable & summary_of_df$group_num >= df$start_num & summary_of_df$group_num <= df$end_num
        max_value <- summary_of_df$max[qualified_rows] %>% unlist %>% max
        min_value <- summary_of_df$max[qualified_rows] %>% unlist %>% min
        df$max_value <- max_value
        df$min_value <- min_value
        df
        df$maxmeanse <- (summary_of_df$mean[qualified_rows] + summary_of_df$se[qualified_rows]) %>% unlist %>% max
        mean <- summary_of_df$mean[qualified_rows] %>% unlist %>% max
        # sd  _max <- summary_of_df$sd[qualified_rows] %>% unlist %>% min
        final_df <- rbind(final_df, df)
        final_df
    }
    
    
    
    ## Get the max and min of the variable through all the groups.
    final_df <- final_df %>% ddply(., "variable", function(each_df){
        each_df$ylim_max <- each_df$max_value %>% max()
        each_df$ylim_min <- each_df$min_value %>% min()
        each_df$ylim_range <- each_df$ylim_max - each_df$ylim_min
        # each_df$maxmeanse
        return(each_df)
    })
    obj@unify_step_by_max_range <- final_df$ylim_range %>% max
    obj@max_value_overall <- final_df$ylim_max %>% max
    
    
    obj@label_position_df <- final_df
    return(obj)
}

#' @title remove distance between non-sig compares. And make the plot more beautyful.
#' @param max_in_range max value in range.
#' @param step_height height for vertical distance between two labels.
#' @param first_stepdown_adjust adjust the height of the first step.
#' @param obj obj
#' @export
return_label.y <- function(max_in_range = each_df$max_value[needs_position],
                           ylim_max, ## max in the data 
                           step_height,
                           fixed_step = F,
                           obj,
                           first_stepdown_adjust = 0.7){
    
    
    "# max_in_range = each_df$max_value[needs_position]"
    
    if(obj@unify_step_as_constant == T & 
       obj@get_step_by_max_instead_of_range == T){
        step_height <- obj@max_value_overall * obj@step
    }else if(obj@unify_step_as_constant == T){
        step_height <- obj@unify_step_by_max_range * obj@step
    }else if(obj@get_step_by_max_instead_of_range == T){
        step_height <- max(ylim_max) * obj@step 
    }
    
    
    first_step_height <- (1 - first_stepdown_adjust) *  step_height ## First label distance from data max.
    label.y <- NULL
    label.y[1] <- max_in_range[1] + first_step_height
    len <- max_in_range %>% length
    if(len > 1){
        for(k in 2:len){
            y1 <- label.y[k-1] + step_height
            y2 <- max_in_range[k] + first_step_height
            label.y[k] <- max(y1, y2)
        }
    }
    return(label.y)
}






#' @title remove distance between non-sig compares. And make the plot more beautyful.
#' @param raw_position original position of labels
#' @param max_in_range max value in range.
#' @param step_height height for vertical distance between two labels.
# recheck_label_position <- function(
#     ## original position
#     raw_position = each_df$label.y[needs_position], 
#     ## base supposed to add height on and put label on it.
#     max_in_range = each_df$max_value[needs_position], 
#     first_stepdown_adjust = 0.7, 
#     
#     step_height  = each_df$ylim_range[1] * obj@step ## each_step.
#     
# ){
#     final_adj <- 0
#     raw_position <- raw_position - step_height * first_stepdown_adjust
#     
#     for(k in 1:length(raw_position)){
#         if(k == 1){next()}
#         if(raw_position[k-1] < max_in_range[k]){
#             # cat(k)
#             raw_position[k:length(raw_position)] <- raw_position[k:length(raw_position)] -  step_height * (k-1)
#             ## to be returned: the num which the label position is 
#         }
#     }
#     
#     
#     
#     
#     # each_df$ylim_max + step_height
#     
#     return(raw_position)
# }




#' @title add labels by the chosen col of p-value.
#' @param obj object for comparing.

add_labels_into_result_df <- function(obj = obj){
    df_with_labels <- obj@result_df
    df_with_labels$p_for_label <- df_with_labels[,obj@p_for_label]
    df_with_labels$label <- df_with_labels$p_for_label %>% as.numeric %>% 
        Loafer::p_to_label(breaks = c(-1,0.001,0.01,0.05,1.1), labels =c("***","* *"," * ","   "))
    obj@result_df <- df_with_labels
    return(obj)
}

#' @title get_long_df for pic. The max, min of each variable will be calculated.
#' @param obj the object for these compare. 

get_long_df <- function(obj = obj){
    wide_df <- data.frame(Sample_ID = rownames(obj@input_df), obj@df_for_test, 
                          check.names = F, stringsAsFactors = F)
    long_df <- wide_df %>% melt(data = ., id.vars = c("Sample_ID","group"), 
                                variavle.name = "variable", value.name = "value")
    
    
    level_to_num_C <-  seq_along(obj@group_levels_in_order_C)
    names(level_to_num_C) <- obj@group_levels_in_order_C
    
    long_df <- long_df %>% ddply(., c("variable", "group"),function(each_df){
        
        
        each_df$group_num <-  each_df$group[1] %>% level_to_num_C[.]
        each_df$mean <- each_df$value %>% mean(., na.rm = T)
        each_df$median   <- each_df$value %>% median(., na.rm = T)
        each_df$sd   <- each_df$value %>% sd(., na.rm = T)
        # each_df$sem <- each_df$sd/(nrow(each_df)**.5)
        each_df$se <- each_df$sd/sqrt(nrow(each_df)) ## Standard Error
        each_df$CI <- qt((1-0.05)/2 + .5, nrow(each_df) - 1) * each_df$se ##  Confidence Interval for alpha = 0.05.
        
        each_df$max <- each_df$value %>% max(., na.rm = T)
        each_df$min <- each_df$value %>% min(., na.rm = T)
        each_df$mean <-  each_df$value %>% mean(., na.rm = T)
        each_df$sd <-  each_df$value %>% sd(., na.rm = T)
        each_df$median <-  each_df$value %>% median(., na.rm = T)
        each_df$IQR_Q1 <- each_df$value %>% quantile(., 0.25,na.rm = T)
        each_df$IQR_Q3 <- each_df$value %>% quantile(., 0.75,na.rm = T)
        
        # each_df$count <- nrow(each_df)
        # each_df$max <- max(each_df$value, na.rm = T)
        # each_df$min <- min(each_df$value, na.rm = T)
        # each_df$range <- 
        # each_df$IQR   <- each_df$value %>% median(., na.rm = T)
        return(each_df)
    }) # %>% head
    
    ### 适配了多组时自动拆分生成 pair1 和 pair 2 变量。
    if("pairwise_group" %in% colnames(obj@result_df) ){
        obj@result_df$pair1 <-  obj@result_df$pairwise_group %>% sub("(.*)-(.*)", "\\1",.)
        obj@result_df$pair2 <-  obj@result_df$pairwise_group %>% sub("(.*)-(.*)", "\\2",.)
    }
    ### 需要自动适配 两组比较的情况：
    
    if(length(obj@group_levels_in_order_C) == 2){
        obj@result_df$pair1 <- obj@group_levels_in_order_C[1]  
        obj@result_df$pair2 <- obj@group_levels_in_order_C[2]
    }
    
    obj@pic_long_df <- long_df
    return(obj)
}







#' @title get compare result by col
#' @param obj the object for these compare. 
#' @param temp_df temp_df by each variable
#' @param meta_name name for each variable

single_col_test <- function(obj = obj, temp_df = temp_df, var_name = var_name){
    obj@test_pattern
    if(obj@test_pattern == "wise"){
        ## if wise pattern was choosen. then the wether para test was carried out.
        IS_para <- wether_para(temp_df = temp_df)
    } else {IS_para = obj@test_pattern}
    if(IS_para == "para") {
        result_df <- para_compare(temp_df = temp_df)
    }else{
        result_df <- non_para_compare(temp_df = temp_df) 
    }
    result_df <- data.frame(Variable = var_name, result_df)
    result_df %>% return
}


#' @title get compare result by col
#' @param obj the object for these compare. 

compare_by_col <- function(obj = obj){
    # obj$data_cleaned
    for(i in 2:ncol(obj@df_for_test)){
        # if(i == 2){pulled_result_df <- data.frame(check.names = F, stringsAsFactors = F)}
        if(i == 2){pulled_result_df <- NULL}
        temp_df <- obj@df_for_test[,c(1,i)]
        var_name <- colnames(obj@df_for_test)[i]
        colnames(temp_df) <- c("group","value")
        test_result_df <- single_col_test(obj = obj,
                                          temp_df = temp_df,
                                          var_name = var_name) ## test by every single col.
        pulled_result_df <- rbind(pulled_result_df, test_result_df)
    }
    colnames(pulled_result_df)[1] <- "variable"
    obj@result_df <- pulled_result_df
    return(obj)
}

#' @title wether_para. To decide wether use para or non-para to compare between groups.
#' @param data_num data in numeric
#' @param group_v group in vector. Besure the group in the same order with the sample.
#' @return IS_para: to suggest para or non-para to be choose considering the distribution and variance of the data.
#' @export

wether_para <- function(temp_df = temp_df){
    data_num = temp_df$value
    group_v = temp_df$group
    # transformed into factor and combined as a data.frame
    group_f = group_v %>% factor()
    data_df <-  data.frame(data_num, group_f)
    # data_df$group_f
    ## normal test.
    if(sd(data_num) == 0){
        IS_para <- "para" ## Doesn't matters anymore cause the data was all the same.
        return(IS_para)
    }
    normal_for_each_group <-  ddply(data_df,.variables = "group_f",
                                    function(each_block){
                                        num_v <-  each_block[,"data_num"]
                                        if(sd(num_v) == 0){ ### in case that all the value 
                                            normal_p <- 1
                                        } else {
                                            normal_test_result <-  shapiro.test(num_v)
                                            normal_p <- normal_test_result$p.value
                                        }
                                        return(normal_p)
                                    })
    Not_Normal <- T %in% (normal_for_each_group[,2] < 0.05) 
    ## Test the sd between groups
    leveneTest_result <-  leveneTest(data_num~group_f, data = data_df)
    p_for_sd <-  leveneTest_result$`Pr(>F)`[1]
    Not_SD_qualified <- p_for_sd < 0.05
    ## choose the method to be used in consided with the two test above.
    if( (is.na(Not_SD_qualified) | (Not_SD_qualified == F))& 
        (is.na(Not_Normal)| (Not_Normal == F)) ){
        IS_para <- "para" ## Doesn't matters anymore cause the data was all the same.
    } else if(Not_SD_qualified | Not_Normal ){ ### if any condition wasn't fit, return the non-para
        IS_para <- "non-para"
    } else{IS_para <-  "para"}
    return(IS_para)
}

#' @title get compare result via non-para method
#' @param temp_df temp_df by each variable 
non_para_compare <- function(temp_df = temp_df){
    
    temp_df$group <- temp_df$group %>% factor()
    
    fit <- kruskal.test(temp_df$value, temp_df$group, na.rm = T)
    p_all <- fit$p.value
    if(is.na(p_all)){p_all <- 1}
    # statistics_all <-  fit$statistic ### 卡方统计量
    ## 构建非参数的后验检验模型。
    group_counts <- temp_df$group %>% unique() %>% length()
    if(group_counts == 2){ ## When group is 2
        final_df <- data.frame(IS_Para = "Non-Para", p_all ,stringsAsFactors = F, check.names = F)
    }else{
        # posthoc_result <-  posthoc.kruskal.nemenyi.test( x = temp_df$Value, g = temp_df$group, dist = c("Tukey", "Chisquare"))
        posthoc_result <-  posthoc.kruskal.nemenyi.test(x = temp_df$value, g = temp_df$group, dist = c("Tukey"))
        # wilcox.test()
        
        
        
        
        # wmc(Value ~ group, data = temp_df)
        p_value_df_width <-  posthoc_result$p.value
        posthoc_df <- p_value_df_width %>% melt() %>% na.omit() ## auto trans NA to 1.
        pairwise_group <- paste(posthoc_df[,1],posthoc_df[,2], sep="-")
        pairwise_p.adj <- posthoc_df$value
        
        
        z <- pairwise.wilcox.test(x = temp_df$value, g = temp_df$group, p.adjust.method = "none")
        p.raw_df <- z$p.value %>% melt() 
        p.raw_df$value[is.na(p.raw_df$value)] <- 1
        matched_num <- match(paste(posthoc_df[,1], posthoc_df[,2]), paste(p.raw_df[,1], p.raw_df[,2]))
        p.raw_df <- matched_num %>% p.raw_df[.,]
        
        pairwise_p.raw <- p.raw_df$value
        
        final_df <-  data.frame(
            # Treat,## 分组比较方式。
            IS_Para = "Non-Para",
            # variable_name,## 变量名
            # statistics_all,
            p_all, # 统计量和p值
            pairwise_group,
            pairwise_p.raw,
            pairwise_p.adj # 后验检验结果
            ,stringsAsFactors = F)
        # final_df$pairwise_p.adj[is.na(final_df$pairwise_p.adj)] <- 1
    }
    
    final_df$p_all[is.na(final_df$p_all)] <- 1
    final_df %>% return
}





#' @title get compare result via para method
#' @param temp_df temp_df by each variable 
para_compare <- function(temp_df = temp_df){
    # input item:
    ## temp_df: a dataframe. 
    ## first col was group and named as "group"
    ## second col was variable value and named as "Value"
    temp_df$group <- temp_df$group %>% factor()
    fit <- aov(value ~ group, data = temp_df)
    p_all <-  summary(fit)[[1]][["Pr(>F)"]][[1]] ##  get p value
    if(is.na(p_all)){p_all <- 1} 
    ## different reaction depended on the numbers of the groups selected.
    if(temp_df$group %>% unique() %>% length() == 2){
        # temp_df$group
        final_df <-  data.frame(IS_Para = "Para", p_all, stringsAsFactors = F, check.names = F)
    }else{
        Tukeyresult <-  TukeyHSD(fit, "group")
        # Tukeyresult
        Tukeyresult_df <- Tukeyresult$group %>% data.frame(.,stringsAsFactors = F)
        pairwise_group <- rownames(Tukeyresult_df)
        Tukeyresult_df$p.adj[is.na(Tukeyresult_df$p.adj)] <- 1
        pairwise_p.adj     <-  Tukeyresult_df$p.adj
        
        # Tukeyresult
        p_raw <- pairwise.t.test(x = temp_df$value, g = temp_df$group,
                                 paired = F, p.adjus.method = "none")
        p_raw.df <- p_raw$p.value %>% melt
        p_raw.df$value[is.na(p_raw.df$value)] <- 1
        match_num <- match(rownames(Tukeyresult_df), paste(p_raw.df[,1], p_raw.df[,2], sep = "-"))
        p_raw.df <- match_num %>% p_raw.df[.,]
        pairwise_p.raw <- p_raw.df$value
        
        # class(Tukeyresult_df)
        final_df <-  data.frame(
            # Treat,## compare method deprecated。
            IS_Para = "Para",
            # variable_name,##  variable name, deprecated
            # statistics_all,
            p_all, # p between any two groups
            pairwise_group,
            pairwise_p.raw,
            pairwise_p.adj # Tukey p adj
            ,stringsAsFactors = F)
    }
    
    final_df$p_all[is.na(final_df$p_all)] <- 1
    final_df %>% return()
}

#' @title get text from screen text which meant to be shown in the screen.
#' @details depraceted function. Tuokuzifangpi - take off pants for fart.
Get_text_from_screen <- function(my_message) { 
    sink(file = "temp file.txt", append = F, type = "output")
    print(my_message)
    sink()
    df_res <- read.delim("temp file.txt", sep = "\n")
    unlink("temp file.txt")
    
    return(df_res)
}

